package pt.atwork.mpadilha.fugae;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.jdo.Extent;
import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;

public class FileUploadServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -6425599075360665553L;
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try{
			response.setContentType("text/html");
			response.getWriter().println("<!DOCTYPE html>");
			response.getWriter().println("<html>");
			response.getWriter().println("  <head>");
			response.getWriter().println("    <meta charset=\"utf-8\" />");
			response.getWriter().println("    <title>Multiple File Upload with BigTable Storage</title>");
			response.getWriter().println("    <link rel=stylesheet href=style.css />");
			response.getWriter().println("  </head>");
			response.getWriter().println("  <body>");
			response.getWriter().println("    <form name=\"upload\" action=\"fileupload\" method=\"POST\" enctype=\"multipart/form-data\">");
			response.getWriter().println("      <input type=\"file\" name=\"files\" multiple=\"multiple\" />");
			response.getWriter().println("      <input type=\"submit\" name=\"submit\" value=\"Upload\" />");
			response.getWriter().println("    </form>");
			
			response.getWriter().println("    <table>");
			response.getWriter().println("      <thead>");
			response.getWriter().println("        <tr><td>&nbsp;</td><td>Filename</td><td>Size</td><td>Date</td></tr>");
			response.getWriter().println("      </thead>");
			response.getWriter().println("      <tbody>");
			
			int i=1;
			long total_size=0;
			
			PersistenceManager pm = PMF.get().getPersistenceManager();
			Extent<MemoryFileItem> extent = pm.getExtent(MemoryFileItem.class);
			for(MemoryFileItem file : extent){
				String filename = file.getName();
				long filesize = file.getSize();
				String display_size = FileUtils.byteCountToDisplaySize(filesize);
				Date date = file.getDate();
				response.getWriter().println("        <tr>");
				response.getWriter().println("          <td>");
				response.getWriter().println("            ");
				response.getWriter().println(i);
				response.getWriter().println("          </td>");
				response.getWriter().println("          <td>");
				response.getWriter().println("            ");
				response.getWriter().println(filename);
				response.getWriter().println("          </td>");
				response.getWriter().println("          <td>");
				response.getWriter().println("            ");
				response.getWriter().println(display_size);
				response.getWriter().println("          </td>");
				response.getWriter().println("          <td>");
				response.getWriter().println("            ");
				response.getWriter().println(date);
				response.getWriter().println("          </td>");
				response.getWriter().println("        </tr>");
				
				i++;
				total_size += filesize;
			}
			extent.closeAll();
			pm.close();
			
			response.getWriter().println("      </tbody>");
			response.getWriter().println("      <tfoot>");
			response.getWriter().println("        <tr><td>&nbsp;</td><td>&nbsp;</td><td>"+FileUtils.byteCountToDisplaySize(total_size)+"</td><td>&nbsp;</td></tr>");
			response.getWriter().println("      </tfoot>");
			response.getWriter().println("    </table>");
			
			response.getWriter().println("  </body>");
			response.getWriter().println("</html>");
		} catch(IOException e){ } 
	}

	@SuppressWarnings("unchecked")
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try{
			// Check that we have a file upload request
			if(ServletFileUpload.isMultipartContent(req)){
				
				MemoryFileItemFactory factory = new MemoryFileItemFactory();
				ServletFileUpload upload = new ServletFileUpload(factory);
				upload.setSizeMax(4*1024*1024); // 4 MB

				// Parse the request
				List<MemoryFileItem> items = upload.parseRequest(req);
				for(MemoryFileItem item : items) {
					item.commit();
				}
			}
		} catch(FileUploadException e){ throw new IOException("Unable to handle uploaded file"); }
		
		doGet(req,resp);
	}

}
